package cn.gdcp.recycleviewtest;

import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import org.w3c.dom.Text;

import java.util.List;

import static android.support.v4.app.ActivityCompat.startActivityForResult;

public class FruitAdapter extends RecyclerView.Adapter <FruitAdapter.ViewHolder>{
       private List<Fruit> mFruitList;
  private   Context context;
    private IOnEditListener listener;
       static class ViewHolder extends RecyclerView.ViewHolder{
            View fruitView;
             ImageView fruitImage;
             TextView fruitName;
             TextView fruitAge;
           ImageView deleteImage;
             public ViewHolder(View view){
                 super(view);
                 fruitView=view;
                 fruitImage=(ImageView)view.findViewById(R.id.fruit_image);
                 fruitName=(TextView)view.findViewById(R.id.fruit_name);
                 fruitAge=(TextView)view.findViewById(R.id.fruit_age);
                  deleteImage=(ImageView)view.findViewById(R.id.delete_image);
                 }
                 }
         public FruitAdapter(List<Fruit> fruitList, Context context,IOnEditListener listener){
           mFruitList=fruitList;
           this.context=context;
           this.listener=listener;
         }

    public ViewHolder onCreateViewHolder( ViewGroup parent, int viewType) {
           View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.fruit_item,parent,false);
          final ViewHolder holder=new ViewHolder(view);
          holder.fruitView.setOnClickListener(new View.OnClickListener() {
              public void onClick(View v) {
                  int position=holder.getAdapterPosition();
                   listener.edit(position);
              }
          });
          holder.deleteImage.setOnClickListener(new View.OnClickListener() {
              public void onClick(View v) {
                  int position=holder.getAdapterPosition();
                mFruitList.remove(position);
                FruitAdapter.this.notifyDataSetChanged();
              }
          });
        return holder;
    }
      public void onBindViewHolder(ViewHolder holder,int position){
          Fruit fruit=mFruitList.get(position);
          holder.fruitImage.setImageResource(fruit.getImageId());
          holder.fruitName.setText(fruit.getName());
          holder.fruitAge.setText(String.valueOf(fruit.getAge()));

      }
    public int getItemCount(){
           return mFruitList.size();
           }
}
